import request from '@/utils/request'

/**
 * 上传文件
 * @param file 文件
 */
export async function uploadFile(file, config) {
  const formData = new FormData()
  formData.append('file', file)
  const res = await request.post('/common/upload', formData, config)
  if (res.code === 0 && res.data) {
    res.url = res.data.filepath
    return res
  }

  return Promise.reject(new Error(res.msg))
}

/**
 * 上传base64文件
 * @param base64 base64数据
 * @param fileName 文件名称
 */
export async function uploadBase64File(base64, fileName) {
  const formData = new FormData()
  formData.append('base64', base64)
  if (fileName)
    formData.append('fileName', fileName)

  const res = await request.post('/file/upload/base64', formData)
  if (res.code === 0 && res.data)
    return res.data

  return Promise.reject(new Error(res.msg))
}

/**
 * 分页查询文件上传记录
 */
export async function pageFiles(params) {
  const res = await request.get('/file/page', { params })
  if (res.code === 0)
    return res.data

  return Promise.reject(new Error(res.msg))
}

/**
 * 删除文件
 */
export async function removeFile(id) {
  const res = await request.delete(`/file/remove/${id}`)
  if (res.code === 0)
    return res.msg

  return Promise.reject(new Error(res.msg))
}

/**
 * 批量删除文件
 */
export async function removeFiles(data) {
  const res = await request.delete('/file/remove/batch', {
    data,
  })
  if (res.code === 0)
    return res.msg

  return Promise.reject(new Error(res.msg))
}
